<?php

namespace app\api\controller;
use think\Controller;
use think\Db;
use fast\Http;
use fast\Random;
use app\api\model\Member as modelMember;

/**
 * swagger: 用户中心
 */
class User extends Base
{
	

    //上传头像
    public function upload(){
       $file = request()->file('file');
       $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/images');
       if($info){
            $data['status'] = 1;
			$data['info'] = $info->getSaveName();
			return json($data);
        }else{
        	$data['status'] = 0;
			$data['info'] = $file->getError();
			return json($data);
        }
    }

    public function getregister()
    {
        $membergroup = db("member_group")->where(['organization_id' => 2, 'status' => '1'])->order("sort desc")->select();

        $result = db("news")->where(["id" => 2, "status" => ['neq', '0']])->find();

        $this->success('获取成功', ['membergroup' => $membergroup, 'result' => $result]);
    }
    public function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public function register()
    {
        $userid = $this->request->request('userid');
        $mobile = $this->request->request('mobile');
        $group_id = $this->request->request('group_id');
        $sex = $this->request->request('sex');
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $password = $this->request->request('password');

        if (!$group_id || !$sex || !$username || !$nickname || !$password || !$mobile ) {
            $this->error("参数不正确");
        }
        if (!isMobile($mobile)) {
            $this->error("手机格式不正确");
        }
        if (\app\api\model\Member::where('mobile', $mobile)->where('id', '<>', $userid)->find()) {
            $this->error("手机号码已存在");
        }
        //监听是否存在短信插件
        // $listen = Hook::get('sms_check');

        // if (!$listen) {
        //     Hook::add('sms_check', function ($data) {
        //         return true;
        //     });
        // }

        // $result = Smslib::check($mobile, $captcha, 'changemobile');
        // if (!$result) {
        //     $this->error("验证码不正确");
        // }
        // $verification = $user->verification;
        // $verification->mobile = 1;
         $user=\app\api\model\Member::where('id', $userid)->find();
         $user->mobile = $mobile;
         $user->group_id = $group_id;
         if($sex=='男')
         $user->sex = 1;
         else
         $user->sex = 0;
         $user->username = $username;
         $user->nickname = $nickname;
         //$user->salt = $Random::alnum();
         $auth = \app\common\library\Auth::instance();         
         $user->password = $auth->getEncryptPassword($password,  $user->salt);
         $user->save();
         $data = [
            'userinfo'  => \app\api\model\Member::where('id', $userid)->find()
        ];
       // Smslib::flush($mobile, 'changemobile');
        $this->success("绑定成功", $data);
    }

    public function login()
    {
        $code = input("code", '');
        $userinfo = input("userinfo/a", []);

        if (empty($code) || count($userinfo) == 0) {
            $this->error('请授权登陆后重试');
        }

        //获取openid,session_key
        $getUserInfo = $this->_getUserInfo($code);

        if (isset($getUserInfo['code']) && $getUserInfo['code'] === 0) {
            $this->error($getUserInfo['msg']);
        }

		//判断是否注册用户
        $user = $this->_login(array_merge($userinfo, $getUserInfo));
        
        if ($user) {
			$auth = \app\common\library\Auth::instance();
            $getUserinfo = $auth->getUserinfo();
            $getUserinfo['avatar'] = cdnurl($auth->avatar, true);
            
            $data = [
                'userinfo'  => $getUserinfo,
                'thirdinfo' => $userinfo
            ];
            $this->success("登录成功", $data);
        }
        else{
            $this->result('', null, '2', null);
        }
		//失败跳转到注册页面
        $this->error("操作失败");
    }
	

    //若用户不存在则注册
    private function _login($userinfo = [])
    {
        
        //查询当前用户是否存在
        $check = db("third_wxapp")->where("open_id", $userinfo['openid'])->find();

         $auth = \app\common\library\Auth::instance();

         $auth->keeptime(0);

        if ($check) {
            db("third_wxapp")->where('id', $check['id'])->update(['session_key'=>$userinfo['session_key'],'unionid'=>$userinfo['unionid'],'user_info'=>json_encode($userinfo),'updatetime'=>time(),'logintime'=>time()]);
            //登陆
            return $auth->direct($check['user_id']);
        }
        // else{
        //     return null;
        // }

        //新用户注册会员
        // 先随机一个用户名,随后再变更为u+数字id
        $username = Random::alnum(20);
        $password = Random::alnum(6);
        $domain = request()->host();

        Db::startTrans();
        try {
            // 默认注册一个会员
            $result = $auth->register($username, $password, $username . '@' . $domain, '', [], 0);
            
            if (!$result) {
                return false;
            }

            $user = $auth->getUser();
            $fields = ['username' => 'wxapp_' . $user->id, 'email' => 'u' . $user->id . '@' . $domain,'group_id'=>1];

            if (isset($userinfo['nickName'])) {
                $fields['nickname'] = $userinfo['nickName'];
            }

            if (isset($userinfo['avatarUrl'])) {
                $fields['avatar'] = htmlspecialchars(strip_tags($userinfo['avatarUrl']));
            }

            // 更新会员资料
            $user = modelMember::get($user->id);
            $user->save($fields);

            // 保存第三方信息
            $values = [
                'user_id' => $user->id,
                'open_id' => $userinfo['openid'],
                'unionid' => $userinfo['unionid'],
                'session_key' => $userinfo['session_key'],
                'user_info' => json_encode($userinfo),
                'createtime' => time(),
                'updatetime' => time(),
                'logintime' => time()
            ];

            db('third_wxapp')->insert($values);
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $auth->logout();
            return false;
        }

        // 写入登录Cookies和Token
        return $auth->direct($user->id);
    }
	//微信获取用户信息
    private function _getUserInfo($code = '')
    {
        $config = cache('db_config_data');

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['app_id'].'&secret='.$config['app_secret'].'&js_code='.$code.'&grant_type=authorization_code';

        $result = json_decode(Http::get($url), 1);

        if (isset($result['errcode']) && $result['errcode'] !==0) {
            return ['code'=>0, 'msg'=>"Login ".$result['errcode']];
        }
        
        return ['session_key'=>$result['session_key'],'openid'=>$result['openid'],'unionid'=>isset($result['unionid'])?$result['unionid']:''];
    }
}